<template>
  <canvas ref="canvasRef" @mousemove="mouseMove"></canvas>
  <div id="plane" :style="{display:planeDisplay,left:planePos.left,top:planePos.top}">
    <p>机柜名称：{{ curShowCabinet.name }}</p>
    <p>机柜温度：{{ curShowCabinet.temperature }}°</p>
    <p>使用情况：{{ curShowCabinet.count }}/{{ curShowCabinet.capacity }}</p>
  </div>
</template>
<script setup lang="ts">
import * as THREE from "three";
import { onMounted, ref, reactive } from "vue";
import MachineRoom from "./MachineRoom";
import {getCabinetByName} from "@/api/request"

const canvasRef = ref<HTMLCanvasElement>(null);
let room: MachineRoom;

// 展示机柜信息
const curShowCabinet = reactive<{
  name: string;
  temperature: number;
  capacity: number;
  count: number;
}>({
  // 名称
  name: "Loading……",
  // 温度
  temperature: 0,
  // 容量
  capacity: 0,
  // 服务器数量
  count: 0,
});

//信息面板的位置
const planePos = reactive<{
  left: number|string;
  top: number|string;
}>({
  left: 0,
  top: 0,
});

// 信息面板的可见性
const planeDisplay = ref("none");

onMounted(() => {
  if(!canvasRef.value) return;
  canvasRef.value.width = window.innerWidth;
  canvasRef.value.height = window.innerHeight;

  room = new MachineRoom(canvasRef.value);
  room.loadGLTF("machineRoom.gltf");
  room.animate();
  //当鼠标划入机柜，显示信息面板
  room.onMouseOverCabinet = ({ name }) => {
      //基于cabinet.name 获取机柜数据
      getCabinetByName(name).then((obj) => {
        Object.assign(curShowCabinet, {...obj,name});
      });
    };
    //当鼠标在机柜上移动，让信息面板随鼠标移动
    room.onMouseMoveCabinet = (left, top) => {
      Object.assign(planePos, { left:left+'px', top:top+'px' });
      planeDisplay.value = "block";
    };
    //当鼠标划出机柜，隐藏信息面板
    room.onMouseOutCabinet = () => {
      planeDisplay.value = "none";
    };
})

// 鼠标移动事件
function mouseMove({ clientX, clientY }) {
  room.selectCabinet(clientX, clientY);
}
</script>
<style>
#plane {
  position: absolute;
  top: 0;
  left: 0;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  padding: 0 18px;
  transform: translate(12px, -100%);
  display: none;
  z-index: 999;
}
</style>
